package srv

import (
	"fmt"
	"github.com/alibaba/sentinel-golang/ext/datasource"
	"github.com/alibaba/sentinel-golang/pkg/adapters/grpc"
	"github.com/alibaba/sentinel-golang/pkg/datasource/nacos"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"

	upbv1 "jmicro/api/user/v1"
	"jmicro/app/pkg/options"
	"jmicro/jmicro/core/trace"
	"jmicro/jmicro/server/rpcserver"
)

func NewNacosDataSource(opts *options.NacosConfig) (*nacos.NacosDataSource, error) {
	//nacos server地址
	sc := []constant.ServerConfig{
		{
			ContextPath: "/nacos",
			Port:        opts.Port,
			IpAddr:      opts.Host,
		},
	}
	//nacos client info
	cc := constant.ClientConfig{
		NamespaceId: opts.Namespace,
		TimeoutMs:   5000,
	}
	//build nacos config client
	client, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": sc,
		"clientConfig":  cc,
	})
	if err != nil {
		return nil, err
	}

	//注册流控规则Handler 如何解析 使用json
	h := datasource.NewFlowRulesHandler(datasource.FlowRuleJsonArrayParser)
	//创建NacosDataSource数据源
	nds, err := nacos.NewNacosDataSource(client, opts.Group, opts.DataId, h)
	if err != nil {
		return nil, err
	}
	return nds, nil
}
func NewUserRPCServer(serverOptions *options.ServerOptions, tltCfg *options.TelemetryOptions,
	uv1 upbv1.UserServer, dataNacos *nacos.NacosDataSource) (*rpcserver.Server, error) {
	//初始化open-telemetry的exporter
	trace.InitAgent(trace.Options{
		tltCfg.Name,
		tltCfg.Endpoint,
		tltCfg.Sampler,
		tltCfg.Batcher,
	})
	//data := mock.NewUsers()
	//交给wire
	//gormDB, err := db.GetDBFactoryOr(cfg.MySQLOptions)
	//if err != nil {
	//	log.Fatal(err.Error())
	//}
	//data := db.NewUsers(gormDB)
	//srv := srv1.NewuserService(data)
	//userver := user.NewUserServer(srv)
	rpcAddr := fmt.Sprintf("%s:%d", serverOptions.Host, serverOptions.Port)
	var opts []rpcserver.ServerOption
	opts = append(opts, rpcserver.WithAddress(rpcAddr))
	opts = append(opts, rpcserver.WithServerEnableTracing(true))
	if serverOptions.EnableLimit {
		opts = append(opts, rpcserver.WithUnaryInterceptor(grpc.NewUnaryServerInterceptor()))
		err := dataNacos.Initialize()
		if err != nil {
			return nil, err
		}
	}
	urpcServer := rpcserver.NewServer(opts...)
	upbv1.RegisterUserServer(urpcServer.Server, uv1)

	return urpcServer, nil

}
